var x;
var y;
var freezeCol = 0;
var SORT_COLUMN;
var freezeColNum;
var vertical = true;
var horizontal = true;
var divContent = null;
var divHeaderRow = null;
var divHeaderRowHeight = 0;
var divHeaderRowTopHeight = 0;
var divHeaderColumn = null;
var divHeaderRowColumn = null;
var headerRowFirstColumn = null;
var sheetArr=[];

/**
 * 对表的特定区域排序
 * 
 * @param {Object}
 *            oSelf 脚本输入单元格，调用时cell的值必须为this
 * @param {int}
 *            iStartRow 开始行
 * @param {int}
 *            iEndRow 结束行
 * @param {int}
 *            iStartCol 开始列
 * @param {int}
 *            iEndCol 结束列
 * @param {int}
 *            iDataType 待排序列的数据类型,（1:字符，2：数字，3:日期）
 * @param {int}
 *            columNum 指定的排序列在表格中的位置(从1开始)
 */
function sortInRectangle(oSelf, iStartRow, iEndRow, iStartCol, iEndCol,
		iDataType, columnNum) {
//	if (navigator.userAgent.indexOf("Firefox") != -1) {
//		return;
//	}
	var columnNumFlag=false;
	var span;
	var cell = oSelf;
	var txt = getInnerText(cell);
	if (cell.innerHTML.toUpperCase().indexOf("SPAN") == -1) {
		cell.innerHTML = txt + "<span class=\"sortarrow\">&nbsp;</span>";
	}
	var startRow = iStartRow;
	var endRow = iEndRow;
	var typeCol = iStartCol;
	var endCol = iEndCol;
	for (var ci = 0; ci < cell.childNodes.length; ci++) {
		if (cell.childNodes[ci].tagName
				&& cell.childNodes[ci].tagName.toLowerCase() == "span") {
			span = cell.childNodes[ci];
		}
	}

	var tr = cell.parentNode;
	var cells = tr.cells;
	var columnIndex = 0;
	var column;

	if (typeof columnNum == "undefined") {
		for (var i = 0; i < cells.length; i++) {
			if (cells[i] != cell) {
				columnIndex += cells[i].colSpan;
			} else {
				break;
			}
		}
		column = columnIndex;
	} else {
		columnNumFlag=true;
		column = columnNum - 1;
	}

	var table = getParent(tr, "TABLE");
	if (table.rows.length <= 1) {
		return;
	}
	
	// 考虑前面有表头单元格合并的情况
	if(!!!columnNumFlag){
		var tempColumn = column;
		for (var i = 1; i < tr.rowIndex; i++) {
			cells = table.rows[i].cells;
			for (var j = 0; j <= tempColumn && j < cells.length; j++) {
				if (cells[j].rowSpan + i > tr.rowIndex) {
					column++;
				}
			}
		}
	}
	

	var sortfn;
	switch (iDataType) {
		case 1 :
			sortfn = sort_ch;
			break;
		case 2 :
			sortfn = sort_numeric;
			break;
		case 3 :
			sortfn = sort_date;
			break;
	}

	SORT_COLUMN = column;
	var newRows = new Array();
	for (j = startRow; j < endRow; j++) {
		newRows[j - startRow] = table.rows[j];
	}

	newRows.sort(sortfn);
	
	if (span.getAttribute("sortdir") == "up") {
//		ARROW = "&nbsp<font face=\"webdings\">6</font>";
		ARROW =  "sortarrow down";
//		span.className = "sortarrow up";
		newRows.reverse();
		span.setAttribute("sortdir", "down");
	} else {
//		ARROW = "&nbsp<font face=\"webdings\">5</font>";
		ARROW =  "sortarrow up";
//		span.className = "sortarrow down";
		span.setAttribute("sortdir", "up");
	}

	// var result = [];

	var resultInnerHtml = [];
	var resultClassName = [];
	for (i = 0; i < newRows.length; i++) {
		resultInnerHtml[i] = [];
		resultClassName[i] = [];

		// result[i] = new Array();
		for (j = 0; j < newRows[0].cells.length; j++) {
			// result[i][j] = newRows[i].cells[j];

			resultInnerHtml[i][j] = newRows[i].cells[j].innerHTML;
			resultClassName[i][j] = newRows[i].cells[j].className;
		}
	}

	var curentCell;
	if (divHeaderColumn != null) {
		for (i = 0; i < newRows.length; i++) {
			for (j = typeCol - 1; j < freezeColNum; j++) {
				curentCell = getFirstChildElement(divHeaderColumn).rows[startRow + i].cells[j];
				curentCell.innerHTML = resultInnerHtml[i][j];
				curentCell.className = resultClassName[i][j];
			}
		}
		for (i = 0; i < newRows.length; i++) {
			for (j = typeCol - 1; j < endCol; j++) {
				curentCell = getFirstChildElement(divContent).rows[startRow + i].cells[j];
				curentCell.innerHTML = resultInnerHtml[i][j];
				curentCell.className = resultClassName[i][j];
			}
		}
	} else {
		for (i = 0; i < newRows.length; i++) {
			for (j = 0; j < endCol; j++) {
				curentCell = table.rows[startRow + i].cells[j];
				curentCell.innerHTML = resultInnerHtml[i][j];
				curentCell.className = resultClassName[i][j];
			}
		}
	}
	var allspans = document.getElementsByTagName("span");
	for (var ci = 0; ci < allspans.length; ci++) {
		if (allspans[ci].className.search(/\bsortarrow\b/) != -1) {
			// if (getParent(allspans[ci], "table") == getParent(cell, "table"))
			// {
//			allspans[ci].innerHTML = "&nbsp;";
			// }
			
			allspans[ci].className = "sortarrow";
		}
	}
	span.className = ARROW;
}


/**
 * 排序扩展出来的数据（定义的报表不能包括合计行）
 */
function sortTableAll(cell, typeCol) {
	startRow = getParent(cell, "tr").sectionRowIndex + 1;
	endRow = getParent(cell, "table").rows.length;

	var cells = getParent(cell, "table").rows[endRow - 1].cells;
	var cellsNum = cells.length;
	var columnNum = 0;
	for (var i = 0; i < cellsNum; i++) {
		columnNum += cells[i].colSpan;
	}

	// endCol = getParent(cell, "table").rows[endRow].cells.length;
	sortTable(cell, startRow, endRow, typeCol, columnNum);
}

/**
 * 对扩展出来的数据进行排序
 * 
 * @param {Object}
 *            cell 脚本输入单元格，调用时cell的值必须为this
 * @param {int}
 *            excludedRowCounts 排除的行数（去除扩展单元格下方的行）
 * @param {int}
 *            dataType 待排序列的数据类型
 * @param {int}
 *            columNum 指定的排序列在表格中的位置
 */
function sortExtendedData(cell, addRow,excludedRowCounts, dataType, columnNum) {

	// 待排序数据的开始行
	startRow = getParent(cell, "tr").sectionRowIndex + cell.rowSpan;
	
	startRow = startRow + addRow;
	// 结束行
	endRow = getParent(cell, "table").rows.length;

	// 获得待排序table的列数
	var columnCounts = getColumnCounts(cell);

	sortInRectangle(cell, startRow, endRow - excludedRowCounts, 1,
			columnCounts, dataType, columnNum);
}

/**
 * 获得该cell对应的table的列数
 */
function getColumnCounts(cell) {
	var cells = getParent(cell, "table").rows[0].cells;
	var cellsNum = cells.length;
	var columnNum = 0;
	for (var i = 0; i < cellsNum; i++) {
		columnNum += cells[i].colSpan;
	}

	return columnNum;
}

function sortTableRange(cell, startRow, excludedRowCounts, startCol, endCol) {
	// 结束行
	endRow = getParent(cell, "table").rows.length;

	sortTable(cell, startRow, endRow - excludedRowCounts, startCol,
			columnCounts);
}

/**
 * 对第startRow行到endRow行和第typeCol列到第endCol之间的数据排序
 * @deprecated
 * 
 * @param {}
 *            cell
 * @param {}
 *            startRow
 * @param {}
 *            endRow
 * @param {}
 *            typeCol
 * @param {}
 *            endCol
 */
function sortTable(cell, startRow, endRow, typeCol, endCol) {
	if (navigator.userAgent.indexOf("Firefox") != -1) {
		return;
	}
	var span;
	var txt = getInnerText(cell);
	if (cell.innerHTML.indexOf("SPAN") == -1) {
		cell.innerHTML = txt + "<span class=\"sortarrow\">&nbsp;</span>";
	}
	var startRow = startRow;
	var endRow = endRow;
	var typeCol = typeCol;
	var endCol = endCol;
	for (var ci = 0; ci < cell.childNodes.length; ci++) {
		if (cell.childNodes[ci].tagName
				&& cell.childNodes[ci].tagName.toLowerCase() == "span") {
			span = cell.childNodes[ci];
		}
	}
	var spantext = getInnerText(span);
	var tr = cell.parentNode;

	var cells = tr.cells;
	var columnIndex = 0;
	for (var i = 0; i < cells.length; i++) {
		if (cells[i] != cell) {
			columnIndex += cells[i].colSpan;
		} else {
			break;
		}
	}

	// var column = typeCol - 1;

	var column = columnIndex;

	var table = getParent(tr, "TABLE");
	if (table.rows.length <= 1) {
		return;
	}
	var itm = getInnerText(table.rows[startRow + 1].cells[column]);
	var sortfn;
	if (itm.match(/^[^0-9a-zA-Z]-?[? ?[\d,.]+%?$/)) {
		sortfn = sort_numeric;
	}
	if (itm.match(/^\d\d\d\d\-\d\d\-\d\d$/)) {
		sortfn = sort_date;
	}
	if (itm.match(/^-?[? ?[\d,.]+%?$/)) {
		sortfn = sort_numeric;
	}
	if (itm.match(/^[\u4e00-\u9fa5]+/)) {
		sortfn = sort_ch;
	}
	if (itm.match(/^[a-zA-Z]+/)) {
		sortfn = sort_en;
	}
	SORT_COLUMN = column;
	var newRows = new Array();
	for (j = startRow; j < endRow; j++) {
		newRows[j - startRow] = table.rows[j];
	}
	newRows.sort(sortfn);
	// if(span.innerHTML=="&nbsp;"){
	// ARROW = "&darr;";
	// span.className = "sortarrow";
	// span.setAttribute("sortdir", "down");
	// }else{
	if (span.getAttribute("sortdir") == "down") {
		ARROW = "&nbsp<font face=\"webdings\">6</font>";
		newRows.reverse();
		span.setAttribute("sortdir", "up");
	} else {
		ARROW = "&nbsp<font face=\"webdings\">5</font>";
		span.className = "sortarrow";
		span.setAttribute("sortdir", "down");
		// }
	}
	var result = new Array();
	for (i = 0; i < newRows.length; i++) {
		result[i] = new Array();
		for (j = 0; j < newRows[0].cells.length; j++) {
			result[i][j] = newRows[i].cells[j].innerHTML;
		}
	}
	if (divHeaderColumn != null) {
		for (i = 0; i < newRows.length; i++) {
			for (j = 0; j < freezeColNum; j++) {
				divHeaderColumn.childNodes[0].rows[startRow + i].cells[j].innerHTML = result[i][j];
			}
		}
		for (i = 0; i < newRows.length; i++) {
			for (j = freezeColNum; j < endCol; j++) {
				divContent.childNodes[0].rows[startRow + i].cells[j].innerHTML = result[i][j];
			}
		}
	} else {
		for (i = 0; i < newRows.length; i++) {
			for (j = 0; j < endCol; j++) {
				table.rows[startRow + i].cells[j].innerHTML = result[i][j];
			}
		}
	}
	var allspans = document.getElementsByTagName("span");
	for (var ci = 0; ci < allspans.length; ci++) {
		if (allspans[ci].className.search(/\bsortarrow\b/) != -1) {
			// if (getParent(allspans[ci], "table") == getParent(cell, "table"))
			// {
			allspans[ci].innerHTML = "&nbsp;";
			// }
		}
	}
	span.innerHTML = ARROW;
}

function getInnerText(el) {
	if (typeof el == "string") {
		return el;
	}
	if (typeof el == "undefined") {
		return el;
	}
//	if (el.innerText) {
//		return el.innerText;
//	}
	var str = "";
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1 :
				str += getInnerText(cs[i]);
				break;
			case 3 :
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}
function getParent(el, pTagName) {
	if (el == null) {
		return null;
	} else {
		if (el.nodeType == 1
				&& el.tagName.toLowerCase() == pTagName.toLowerCase()) {
			return el;
		} else {
			return getParent(el.parentNode, pTagName);
		}
	}
}

function sort_date(a, b) {
	aa = getInnerText(a.cells[SORT_COLUMN]);
	bb = getInnerText(b.cells[SORT_COLUMN]);

	dt1 = aa.substring(0, 4) + aa.substring(5, 7) + aa.substring(8, 10);
	dt2 = bb.substring(0, 4) + bb.substring(5, 7) + bb.substring(8, 10);
	if (dt1 == dt2) {
		return 0;
	}
	if (dt1 < dt2) {
		return -1;
	}
	return 1;
}

function sort_numeric(a, b) {
	var sortedColumnAText = getInnerText(a.cells[SORT_COLUMN]);
	var aa = "0";
	if (sortedColumnAText == "") {
		aa = "0";
	} else {
		aa = sortedColumnAText.replace(/[^0-9.-]/g, "");
	}

	var bb = "0";
	var sortedColumnBText = getInnerText(b.cells[SORT_COLUMN]);
	if (sortedColumnBText == "") {
		bb = "0";
	} else {
		bb = sortedColumnBText.replace(/[^0-9.-]/g, "");
	}

	return parseFloat(aa) - parseFloat(bb);
}

function sort_ch(a, b) {
	aa = getInnerText(a.cells[SORT_COLUMN]);
	bb = getInnerText(b.cells[SORT_COLUMN]);
	return aa.localeCompare(bb);
}
function sort_en(a, b) {
	aa = getInnerText(a.cells[SORT_COLUMN]).toLowerCase();
	bb = getInnerText(b.cells[SORT_COLUMN]).toLowerCase();
	return aa.localeCompare(bb);
}
/**
 * 
 * @param {Object} a
 * @param {Object} b
 * @param {Object} c
 * @param {Object} sheetNo sheet的序号（从1开始）
 */
function appendStyle(a, b, c,sheetNo) {
	CreateFreezeTable(document.getElementById("innerDiv" + (sheetNo || "0") ), a, b, c);
	var sheetParam={};
	sheetParam.x=x;
	sheetParam.y=y;
	sheetParam.freezeCol=freezeCol;
	sheetParam.SORT_COLUMN=SORT_COLUMN;
	sheetParam.freezeColNum=freezeColNum;
	sheetParam.vertical=vertical;
	sheetParam.horizontal=horizontal;
	sheetParam.divContent=divContent;
	sheetParam.divHeaderRow=divHeaderRow;
	sheetParam.divHeaderRowHeight=divHeaderRowHeight;
	sheetParam.divHeaderRowTopHeight=divHeaderRowTopHeight;
	sheetParam.divHeaderColumn=divHeaderColumn;
	sheetParam.divHeaderRowColumn=divHeaderRowColumn;
	sheetParam.headerRowFirstColumn=headerRowFirstColumn;
	sheetArr.push(sheetParam);
}
function CreateFreezeTable(content, a, b, c) {
	if (content != null) {
		freezeCol = 0;
		divHeaderRowHeight = 0;
		divHeaderRowTopHeight = 0;

		
		freezeColNum = c;
		divContent = content;

		divContentTable = getFirstChildElement(divContent);
		var tbody = getFirstChildElement(divContentTable);
		
		var maxRow=tbody.rows.length;
		var maxCol=tbody.rows[0].cells.length;
		
		for (i = 0; i < a && i<maxRow; i++) {
			divHeaderRowHeight = divHeaderRowHeight
					+ tbody.rows[i].offsetHeight;
			// modified for jinchuan
			if (dojo.isIE === 8) {
				var styleHeight = Math.ceil(parseInt(tbody.rows[i].style.height) * 4 / 3);
				if (styleHeight) {
					var span = tbody.rows[i].offsetHeight / styleHeight;
					i += span > 1 ? (span - 1) : 0;
				}
			}
		}
		
		for (i = 0; i < b && i<maxRow; i++) {
			divHeaderRowTopHeight = divHeaderRowTopHeight
					+ tbody.rows[i].offsetHeight;
			// modified for jinchuan
			if (dojo.isIE === 8) {
				var styleHeight = Math.ceil(parseInt(tbody.rows[i].style.height) * 4 / 3);
				if (styleHeight) {
					var span = tbody.rows[i].offsetHeight / styleHeight;
					i += span > 1 ? (span - 1) : 0;
				}
			}
		}
		
		var headerRow = a<=maxRow-1?tbody.rows[a]:tbody.rows[maxRow-1];
				
		x = divContentTable.offsetWidth;
		y = divContentTable.offsetHeight;
		if(window.navigator.userAgent.indexOf('Chrome')>-1){
			divContent.style.padding="0";
		}
		
		divHeaderRow = divContent.cloneNode(true);
		divHeaderRow.id = "divHeaderRow";
		divHeaderRow.style.zIndex = "100";
		var divHeaderRowTable = getFirstChildElement(divHeaderRow);
		
//		divHeaderRowTop = divContent.cloneNode(true);
//		
//		divHeaderRowTop.id = "divHeaderRowTop";
		
		divHeaderRow.style.height = divHeaderRowHeight + 1 + "px";
		
		divHeaderRow.style.overflow = "hidden";
		
//		divHeaderRowTop.style.height = divHeaderRowTopHeight + "px";
//		divHeaderRowTop.style.overflow = "hidden";
		
		divContentTable.style.position = "absolute";
		if(a<=maxRow-1){//满足条件
			divContent.parentNode.insertBefore(divHeaderRow, divContent);
			divContentTable.style.top = -divHeaderRowHeight - 1 + "px";
		}
		
	//	divContentTable.style.left= 0.1;
		divHeaderRowColumn = divHeaderRow.cloneNode(true);
		
		
		divHeaderRowColumn.id = "divHeaderRowColumn";
		
		headerRowFirstColumn = headerRow.cells[0];
		divHeaderColumn = divContent.cloneNode(true);
		
		divHeaderColumn.id = "divHeaderColumn";
		
		divContent.style.position = "relative";
//		divContent.style.zIndex = -1;
		divContent.style.top = 0;
		if(a<=maxRow-1){//满足条件
			divContent.parentNode.insertBefore(divHeaderColumn, divContent);
		}
		divContent.style.left = 0;
		divContentTable.style.position = "absolute";
		divHeaderColumn.style.top = divHeaderRowHeight + 1 + "px";
		for (i = 0; i < c && i<maxCol; i++) {
			freezeCol = freezeCol + headerRow.cells[i].offsetWidth;
		}
		// modified for jinchuan
		if (dojo.isIE === 8) {
			freezeCol += 1;
		}
		divHeaderColumn.style.width = freezeCol + 1 + "px";
		divHeaderColumn.style.overflow = "hidden";
		divHeaderColumn.style.zIndex = "99";
		divHeaderColumn.style.position = "absolute";
		divHeaderColumn.style.left = "0";
		addScroll(divHeaderColumn, divContent, "vertical");
		x = x - freezeCol;
		divContent.parentNode.insertBefore(divHeaderRowColumn, divContent);
	}
	divHeaderRowColumn.style.position = "absolute";
	divHeaderRowColumn.style.left = "0";
	divHeaderRowColumn.style.top = "0";
	divHeaderRowColumn.style.width = freezeCol + 1 + "px";
	divHeaderRowColumn.overflow = "hidden";
	divHeaderRowColumn.style.zIndex = "103";
	addScroll(divHeaderRow, divContent, "horizontal");
//	addScroll(divHeaderRowTop, divContent, "horizontal");
	//addScroll(divHeaderRowColumn, divHeaderRowTop, "horizontal");
//	window.onresize = ResizeScrollArea;
	window.onresize = _.debounce(ResizeScrollAreaSheet, 300);
	ResizeScrollArea();
}
function ResizeScrollAreaSheet() {
	for (var i = 0; i < sheetArr.length; i++) {
		var sheetParam = sheetArr[i];
		x = sheetParam.x;
		y = sheetParam.y;
		freezeCol = sheetParam.freezeCol;
		SORT_COLUMN = sheetParam.SORT_COLUMN;
		freezeColNum = sheetParam.freezeColNum;
		vertical = sheetParam.vertical;
		horizontal = sheetParam.horizontal;
		divContent = sheetParam.divContent;
		divHeaderRow = sheetParam.divHeaderRow;
		divHeaderRowHeight = sheetParam.divHeaderRowHeight;
		divHeaderRowTopHeight = sheetParam.divHeaderRowTopHeight;
		divHeaderColumn = sheetParam.divHeaderColumn;
		divHeaderRowColumn = sheetParam.divHeaderRowColumn;
		headerRowFirstColumn = sheetParam.headerRowFirstColumn;
		ResizeScrollArea();
	}
}
function ResizeScrollArea() {
//	if(searchReport_state){
//		var height = document.body.clientHeight+360;
//	}else{
//		var height = document.documentElement.clientHeight;
//	}
	var height = document.documentElement.clientHeight;//divContent可能的最大高度
	height=height - divHeaderRowHeight
			- 80;
	//查询类型报表中
	if(height<0){
		height += 80;
		if(height<0){
			height = document.documentElement.clientHeight;
		}
	}
	var width = document.documentElement.clientWidth - 50;
	var headerRowsWidth = 0;
	//修改ie8兼容模式下表格对不齐
	//divContentTable.style.width = x + "px";
	//divContentTable.style.height = y + "px";
	if (divHeaderRowColumn != null) {
		headerRowsWidth = divHeaderRowColumn.offsetWidth;
	}
	// modified for jinchuan
	var borderWidth=0;
	if (dojo.isIE === 8) {
		borderWidth=1;
	}

	var divContentRealWidth=divContentTable.offsetWidth;//divContent的实际宽度
    if(divContentTable.scrollWidth>divContentTable.offsetWidth){
    	divContentRealWidth=divContentTable.scrollWidth;
    }
	if (divContentRealWidth > width) {
		divContent.style.width =width  + "px";
//		divContent.style.width = Math.max(width - headerRowsWidth, 0)  + "px";
		divContent.style.overflowX = "scroll";
		divContent.style.overflowY = "auto";
		if (divHeaderRow != null) {
			divHeaderRow.style.width = width+borderWidth + "px";
		}
	} else {
		divContent.style.width = divContentRealWidth + "px";
		divContent.style.overflowX = "auto";
		divContent.style.overflowY = "auto";
		if (divHeaderRow != null) {
			divHeaderRow.style.width = divContentRealWidth+borderWidth + "px";
		}
	}
	

	if (y > height + divHeaderRowHeight) {
		divContent.style.height = height + "px";
		divContent.style.overflowY = "scroll";
	} else {
		divContent.style.height=height + "px";
//		divContent.style.height = y - divHeaderRowHeight + "px";
		divContent.style.overflowY = "hidden";
//		divContent.style.width = divContent.offsetWidth + headerRowsWidth + "px";
	}
	if (divHeaderColumn != null) {
//		divHeaderColumn.style.height = divContent.offsetHeight + "px";
		divHeaderColumn.style.height = height + "px";
	}
	var scrollHD=divContent.offsetWidth-divContent.clientWidth||17;
	if (divContent.style.overflowY == "scroll") {
		divContent.style.width = divContent.offsetWidth + scrollHD + "px";
	}
	if (divContent.style.overflowX == "scroll") {
		divContent.style.height = height + scrollHD + "px";
	}
	if(document.getElementById("tableContainer")){
		document.getElementById("tableContainer").style.width=width+'px';
	}
	//	divContent.parentNode.insertBefore(divHeaderRowTop, divContent);zj
//	divHeaderRowTop.style.zIndex = "101";
//	divHeaderRowTop.style.position = "absolute";
//	divHeaderRowTop.style.top = "0";
//	divHeaderRowTop.style.left = "0";
//	
//	divHeaderRowTop.style.width = divHeaderRow.style.width;
//	divContent.parentNode.style.width = divContent.offsetWidth
//			+ headerRowsWidth  + "px";
}

function getScroll(oElement) {
	return function(event) {
		event = window.event || event;
		var target = event.srcElement || event.target;
		
		if (oElement._scrollSyncDirection == "horizontal"
				|| oElement._scrollSyncDirection == "both") {
			oElement.scrollLeft = target.scrollLeft;
		}
		if (oElement._scrollSyncDirection == "vertical"
				|| oElement._scrollSyncDirection == "both") {
			oElement.scrollTop = target.scrollTop;
		}
	};
}

function addScroll(fromElement, toElement, direction) {
	removeScroll(fromElement);
	fromElement._syncScroll = getScroll(fromElement);
	fromElement._scrollSyncDirection = direction;
	fromElement._syncTo = toElement;
	if(toElement.attachEvent){
		toElement.attachEvent("onscroll", fromElement._syncScroll);	
	} else {
		toElement.addEventListener("scroll",fromElement._syncScroll,false);
	}
}

function removeScroll(fromElement) {
	if (fromElement._syncTo != null) {
		if(fromElement._syncTo.detachEvent){
			fromElement._syncTo.detachEvent("onscroll", fromElement._syncScroll);			
		} else {
			fromElement._syncTo.removeEventListener("scroll", fromElement._syncScroll,false);	
		}
	}
	fromElement._syncTo = null;
	fromElement._syncScroll = null;
	fromElement._scrollSyncDirection = null;
}

/**
 * 获得节点的第一个子元素
 * @param {Object} node
 */
function getFirstChildElement(node){
    var x = node.firstChild;
    while (x.nodeType != 1) {
        x = x.nextSibling;
    }
    return x;
    
}

function sortReport(name,value,param){

	// 处理导航条
	if (typeof urNavLevels != "undefined" && urNavLevels.length > 1) {
	  	var level = urNavLevels.pop();
	  	var lastLevel = urNavLevels.pop();
  		var result = getNavStepFromLevel(lastLevel);
		var rName = result.name;
		var step = result.step;
		lastLevel = rName + ';' + (step + 1);
		urNavLevels.push(lastLevel);
		urNavLevels.push(level);
	}
  resultForm.action=WEB_APP_NAME+'/'+"Report-Guage."+window.action_suffix+"?newReport=true&unieap_report_reprocess=true";
  var input = document.createElement('input');
  input.setAttribute("type", "hidden");
  input.setAttribute("name", name);
  input.setAttribute("value", value);
  resultForm.appendChild(input);
  if(param){
	  for(var obj in param){
		  var input = document.createElement('input');
		  input.setAttribute("type", "hidden");
		  input.setAttribute("name", param[obj].name);
		  input.setAttribute("value", param[obj].value);
		  resultForm.appendChild(input);
	  }
  }
  
  // 处理fitPage参数
  if (fitPage) {
  	resultForm.action += "&fitPage=" + fitPage;
  }
  if (typeof urNavLevels != "undefined" && urNavLevels.length > 1) {
	urNavLevels.pop();
  	resultForm.action += "&ur_nav_levels=" + encodeto64(JSON.stringify(urNavLevels)).replace(/\+/g, '-').replace(/\//g, '_');
  }
  if(isReportNav){
  	resultForm.action += "&isReportNav="+isReportNav;
  }
  resultForm.target = "_self";
  //showProgressBar('true',resultForm);
  resultForm.submit();

}
if (htmlExportType !== "1" && category !=="2" && !reportResize){//页面大小分页、填报报表、行列拖拽报表不执行
	dojo.addOnLoad(function(){setTimeout(resizeSheets,0)});
}

dojo.addOnLoad(freeze);
function resizeSheets(){
	var pagePositionDiv = document.getElementById("pagePosition");
	pagePositionDiv.style.display = "block";
	var Sheets=$("#tabContents").children();
	var maxHeight = 0;
	for(var i = 0; i < Sheets.length; i++){
		maxHeight = Math.max(resize(i, Sheets.length, maxHeight),maxHeight);
	}
	if (Sheets.length > 1) { // 多布局修正高度
		var reportContentDiv = document.getElementById("reportContentDiv");
		maxHeight = maxHeight + 45 + 27; // 多布局名称与分页器高度;
		reportContentDiv.style.height = maxHeight + "px";
	}
}
function resize(i, multiSheet) {
	var height = document.documentElement.clientHeight;
	var width = document.documentElement.clientWidth;
	var innerDiv = document.getElementById("innerDiv" + i);
	var reportTableDiv = document.getElementById("reportTable");
	var dataTableDiv = document.getElementById("dataTable");
	if (i != 0){
		dataTableDiv = document.getElementById("dataTable" + i);
	}
	var reportContentDiv = document.getElementById("reportContentDiv");
	var reportPageDiv = document.getElementById("reportPage");
	
	height = height - 70;
	var innerHeight = height;
	width = width - 30;
	if (!fitPage && dataTableDiv.offsetHeight < height){
		height = dataTableDiv.offsetHeight + 10;
	}
	if (sLinage == -1){ // 去掉分页器高度
		height = height + 28;
		innerHeight=innerHeight+28;
		reportPageDiv.style.height = "17px";
	}
	if (multiSheet > 1){
		height = height - 27; // 去掉多布局名称高度
		innerHeight=innerHeight-27;
	}
	innerDiv.style.maxHeight = innerHeight + "px";
//	innerDiv.style.maxWidth = width  + "px";
	innerDiv.style.width = width  + "px";
	if (!fitPage){
		innerDiv.style.overflow = "auto";
		reportContentDiv.style.width = "100%";
	} else {
		reportContentDiv.style.width = null;
	}
	
	if (i == 0 && !fitPage && !mobileFitPage && !multiSheets && reportAlign == "true"){
		var tableContainer = document.getElementById("tableContainer");
		tableContainer.style.width = innerDiv.style.width;
		dataTableDiv.style.margin = "0px auto";
	}	
	return height;
//	reportTableDiv.style.margin = "0px 5px";
}
function freeze(){
	if(window.isFreezeReport){
		freezeSheets();
		window.onresize = _.debounce(freezeSheets, 300);
	}
}
function freezeSheets(){
	var Sheets=$("#tabContents").children();
	for(var i=0;i<Sheets.length;i++){
		freezeAdapt(i);
	}
}
function freezeAdapt(nthSheet) {
	var HDPadding=10;
	var height = document.documentElement.clientHeight;//divContent可能的最大高度
	var width = document.documentElement.clientWidth - 50;
	var iconTable=document.getElementById("iconTable");
	var tableContainer=document.getElementById("tableContainer");
	var dataTable=nthSheet==0?document.getElementById("dataTable"):document.getElementById("dataTable"+nthSheet);
	var div1=document.getElementById("rptfreeze_"+nthSheet+"_div1");
	var div2=document.getElementById("rptfreeze_"+nthSheet+"_div2");
	var div3=document.getElementById("rptfreeze_"+nthSheet+"_div3");
	var div4=document.getElementById("rptfreeze_"+nthSheet+"_div4");
	var table1=document.getElementById("rptfreeze_"+nthSheet+"_table1");
	var table2=document.getElementById("rptfreeze_"+nthSheet+"_table2");
	var table3=document.getElementById("rptfreeze_"+nthSheet+"_table3");
	var table4=document.getElementById("rptfreeze_"+nthSheet+"_table4");
	var vEventFlag=true;
	var hEventFlag=true;
	if(!div1){
		return;
	}
	var div1Height=table1.offsetHeight;
	var div1Width=table1.offsetWidth;
	if(iconTable){
		height=height-iconTable.offsetHeight;
	}
	height=height - div1Height- 80;//div3 height
	//查询类型报表中
	if(height<0){
		height += 80;
		if(height<0){
			height = document.documentElement.clientHeight;
		}
	}
	width=width-div1Width;//div2 width
	if(!div2){//rowfreeze
		if(table3.offsetHeight>height){
			div3.style.height =height  + "px";
			div3.style.overflowY = "scroll";
		}else{
			div3.style.height =table3.offsetHeight  + "px";
			div3.style.overflowY = "hidden";
		}
		div3.style.width=table3.offsetWidth+HDPadding+"px";
		var scrollHD=div3.offsetWidth-div3.clientWidth||17;
		if (div3.style.overflowY == "scroll") {
			div3.style.width = div3.offsetWidth + scrollHD + "px";
		}
		if(dataTable){
			dataTable.style.width=div3.style.width;
		}
		if(tableContainer){
			tableContainer.style.width=width+div1Width+'px';
		}
	}else if(!div3){//col freeze
		if(table2.offsetWidth+HDPadding>width){
			div2.style.width=width+"px";
			div2.style.overflowX="scroll";
		}else{
			div2.style.width=table2.offsetWidth+HDPadding+"px";
			div2.style.overflowX="hidden";
		}
		div2.style.height=table2.offsetHeight+"px";
		var scrollHD=div2.offsetHeight-div2.clientHeight||17;
		if (div2.style.overflowX == "scroll") {
			div2.style.height = div2.offsetHeight + scrollHD + "px";
		}
		if(dataTable){
			dataTable.style.width=div2.offsetWidth+div1Width+'px';
			
		}
		if(tableContainer){
			tableContainer.style.width=width+div1Width+'px';
		}
		
	}else if(div4){
		if(table4.offsetHeight<height){
			div4.style.height =table4.offsetHeight  + "px";
			div4.style.overflowY = "hidden";
			div3.style.height=table4.offsetHeight+"px";
			div3.style.overflow="hidden";
		}else{
			div4.style.height =height  + "px";
			div4.style.overflowY = "scroll";
			div3.style.height=height+"px";
			div3.style.overflow="hidden";
			if(vEventFlag){
				addScroll(div3, div4, "vertical");
				vEventFlag=false;
			}
		}
		
		if(table4.offsetWidth+HDPadding<width){
			div4.style.width=table4.offsetWidth+HDPadding+"px";
			div4.style.overflowX="hidden";
			div2.style.width=table4.offsetWidth+HDPadding+"px";
			div2.style.overflow="hidden";
		}else{
			div4.style.width=width+"px";
			div4.style.overflowX="scroll";
			div2.style.width=width+"px";
			div2.style.overflow="hidden";
			if(hEventFlag){
				addScroll(div2, div4, "horizontal");
				hEventFlag=false;
			}
		}
		var scrollHD=div4.offsetWidth-div4.clientWidth||div4.offsetHeight-div4.clientHeight||17;
		if (div4.style.overflowY == "scroll") {
			div4.style.width = div4.offsetWidth + scrollHD + "px";
		}
		if (div4.style.overflowX == "scroll") {
			div4.style.height = div4.offsetHeight + scrollHD + "px";
		}
		if(dataTable){
			dataTable.style.width=div1Width+div4.offsetWidth  + "px";
		}
		if(tableContainer){
			tableContainer.style.width=width+div1Width+'px';
		}
	}
}